import oss2
import uuid
import os
from django.conf import settings
from datetime import datetime
import logging

logger = logging.getLogger(__name__)


class OSSUploader:
    """阿里云OSS上传工具类"""
    
    def __init__(self):
        """初始化OSS客户端"""
        try:
            auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET)
            self.bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME)
        except Exception as e:
            logger.error(f"OSS初始化失败: {e}")
            raise e
    
    def upload_file(self, file, folder='images'):
        """上传文件到OSS"""
        try:
            # 验证文件
            if not file:
                logger.error("上传文件为空")
                return None
            
            # 生成唯一文件名
            ext = os.path.splitext(file.name)[1].lower()
            if not ext:
                ext = '.jpg'  # 默认扩展名
            
            filename = f"{uuid.uuid4().hex}{ext}"
            
            # 按日期分文件夹
            date_path = datetime.now().strftime('%Y/%m/%d')
            key = f"{folder}/{date_path}/{filename}"
            
            # 重置文件指针到开始位置
            file.seek(0)
            
            # 上传文件
            result = self.bucket.put_object(key, file.read())
            
            if result.status == 200:
                # 返回文件URL
                if settings.OSS_CUSTOM_DOMAIN:
                    file_url = f"{settings.OSS_CUSTOM_DOMAIN}/{key}"
                else:
                    file_url = f"https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/{key}"
                
                logger.info(f"文件上传成功: {file_url}")
                return file_url
            else:
                logger.error(f"OSS上传失败，状态码: {result.status}")
                return None
                
        except Exception as e:
            logger.error(f"OSS上传异常: {e}")
            return None
    
    def delete_file(self, file_url):
        """删除OSS中的文件"""
        try:
            # 从URL中提取key
            if settings.OSS_CUSTOM_DOMAIN and settings.OSS_CUSTOM_DOMAIN in file_url:
                key = file_url.replace(f"{settings.OSS_CUSTOM_DOMAIN}/", "")
            else:
                # 从标准OSS URL中提取key
                domain = f"https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/"
                key = file_url.replace(domain, "")
            
            # 删除文件
            result = self.bucket.delete_object(key)
            
            if result.status == 204:
                logger.info(f"文件删除成功: {key}")
                return True
            else:
                logger.error(f"OSS删除失败，状态码: {result.status}")
                return False
                
        except Exception as e:
            logger.error(f"OSS删除异常: {e}")
            return False
    
    def file_exists(self, file_url):
        """检查文件是否存在"""
        try:
            # 从URL中提取key
            if settings.OSS_CUSTOM_DOMAIN and settings.OSS_CUSTOM_DOMAIN in file_url:
                key = file_url.replace(f"{settings.OSS_CUSTOM_DOMAIN}/", "")
            else:
                domain = f"https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/"
                key = file_url.replace(domain, "")
            
            # 检查文件是否存在
            return self.bucket.object_exists(key)
            
        except Exception as e:
            logger.error(f"检查文件存在性异常: {e}")
            return False


# 创建全局实例
def get_oss_uploader():
    """获取OSS上传器实例"""
    try:
        return OSSUploader()
    except Exception as e:
        logger.error(f"创建OSS上传器失败: {e}")
        return None